#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#if defined(OS_ANDROID)||defined(OS_LINUX_SOC)
#include <err.h>
#endif
#include <libmslog/mslog.h>
#include <libmscommon/mscommon.h>
#include "msprotocol.h"

#define  FLAG "FIFO_PTL"

static int fifo_open(URLContext *h)
{
	char *fifoNname=h->url;
	MSFIFOBLOCKContext * pmsfifo_ctt= msfifo_api_blockInit(1*ms_MB,fifoNname);

	h->fd =(pmsfifo_ctt);
	return h->fd ;
}

static int fifo_read(URLContext *h, unsigned char *buf, int size)
{
	MSFIFOBLOCKContext * pmsfifo_ctt=(MSFIFOBLOCKContext * ) h->fd;
	ms_s32 len=ms_min(size, msfifo_api_blockSizeUsed(pmsfifo_ctt));
	msfifo_api_blockOut(pmsfifo_ctt, buf, len, ms_null);
	return 0;
}

static int fifo_write(URLContext *h, unsigned char *buf, int size)
{
	MSFIFOBLOCKContext * pmsfifo_ctt=(MSFIFOBLOCKContext * ) h->fd;
	if( msfifo_api_blockSizeLeft(pmsfifo_ctt)<size) {/* No Space left */
		msfifo_api_blockReset(pmsfifo_ctt);	
		ms_waring("[%s]Waring:pmsfifo_ctt overflow,reset ",pmsfifo_ctt->name);
	}
	msfifo_api_blockIn(pmsfifo_ctt, buf, size, ms_null);
	return 0;
}

static int fifo_close(URLContext *h)
{
	MSFIFOBLOCKContext * pmsfifo_ctt=(MSFIFOBLOCKContext * ) h->fd;
	msfifo_api_blockDeinit(&pmsfifo_ctt);
	return 0;
}

URLProtocol ffurl_fifo_protocol = {
	.nameDes	= msptc_getPtcNameDes(msptc_fifo),
	.url_open	= fifo_open,
	.url_read	= fifo_read,
	.url_write	= fifo_write,
	.url_close	= fifo_close,
};
